#include <string.h>
#include <sys/time.h>
#include <sys/epoll.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>

#include "Public.h"
#include "Log.h"
#include "Connect.h"
#include "Message.h"
#include "Loop.h"

namespace sevent{

Connect::Connect():_fd(-1), _status(NOTUSE), _count(-1){
	pthread_mutex_init(&_mutex, NULL);
}

Connect::Connect(int fd, Address addr)
:_fd(fd), _peerAddr(addr), _status(NOTUSE), _count(-1){
	pthread_mutex_init(&_mutex, NULL);
}

Connect::Connect(int fd, Address addr, Loop* loop)
:_fd(fd), _peerAddr(addr), _loop(loop), _status(NOTUSE), _count(-1){
	pthread_mutex_init(&_mutex, NULL);
}

Connect::~Connect(){
	if(_fd != -1){
		sevent::tcpClose(_fd);
	}
	pthread_mutex_destroy(&_mutex);
}

int Connect::read(void *buf, int len, int timeout){
	if(!alive())
		return -2;
	return sevent::tcpRead(_fd, buf, len, timeout);
}

int Connect::write(void *buf, int len, int timeout){
	if(!alive())
		return -2;
	return sevent::tcpWrite(_fd, buf, len ,timeout);
}

bool Connect::alive(){ 
	if(_fd == -1)
		return false;
	if(_fd == 0)
		return false;
	return true;
}

int Connect::close(){
	LOG_DEBUG_VA("Connect %x:%d:%d close", this, fd(), _count);
	int count = subCount();
	if(count == -1){
		shutdown();
	}
}

int Connect::shutdown(){
	LOG_DEBUG_VA("Connect %x:%d:%d shutdown", this, fd(), _count);
	int ret = getLoop()->deleteConnect(_fd);
	if(ret == -1){
		LOG_ERROR_VA("Connect %x:%d:%d Loop::deleteConnect error", this, fd(), _count);
	}
	sevent::tcpClose(_fd);
	_count = -1;
	_fd = -1;
}

bool Connect::inUsing(){
	if(_count == -1){
		return false; 
	}else if(_count == 0){
		return true;
	}else{
		return true;
	}
}

int Connect::lock(){
	pthread_mutex_lock(&_mutex);
	return 0;
}

int Connect::unLock(){
	pthread_mutex_unlock(&_mutex);
	return 0;
}

int Connect::addCount(){
	lock();
	++_count;
	int count = _count;
	unLock();
	return count;
}

int Connect::subCount(){
	lock();
	--_count;
	int count = _count;
	unLock();
	return count;
}


}

